#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include "const.h"

int Process(char *user);
int CmRandom(int min_val, int max_val);


int main(int argc, char *argv[])
{
    int times, count;
    char user[10];
    time_t start, end, user_start, user_end;

    if(argc!=2)  times=100;
    else  times=atoi(argv[1]);
    if(times==0)  times=100;

    if(DbsConnect())  exit(1);

    time(&start); 
    for(count=0; count<times; count++)
    {
/*
        time(&user_start); 
*/
        sprintf(user, "test%04d", CmRandom(0,9999));
        if(Process(user))
        {
            printf("user_log_dyna query %d times fail\n", times);
            exit(1);
        }
        printf("user no.%04d %s finished\n", count+1, user);
/*
        time(&user_end);
        printf("user %s time cost:%d seconds\n",
            user, user_end-user_start);
*/
    }
    time(&end);
    printf("time cost total:%d seconds\n", end-start);

    exit(0);
}


int Process(char *user)
{
    int result, day, count=0;
    char content[500], sql[200];

    for(day=1; day<=15; day++)
    {
        sprintf(sql, "select content from user_log_200101%02d where loginname='%s' order by log_id desc",
            day, user);
        if(DbsUSER_LOG_CUR_Dyna(DBS_OPEN, sql, content)!=DB_OK)
        {
            printf("open cursor fail\n");
            return -1;
        }
        while(1)
        {
            result=DbsUSER_LOG_CUR_Dyna(DBS_FETCH, sql, content);
            if(result!=DB_OK && result!=DB_NOTFOUND)
            {
                printf("fetch cursor fail\n");
                return -1;
            }
            if(result==DB_NOTFOUND)  break;
/*
            count++;
            if(count>=100)  break;
*/
        }
        if(DbsUSER_LOG_CUR_Dyna(DBS_CLOSE, sql, content)!=DB_OK)
        {
            printf("close cursor fail\n");
            return -1;
        }
        if(count>=100)  break;
    }

    return 0;
}


int CmRandom(int min_val, int max_val)
{
    struct timeval uTime;
    int  delta_val;
    int  ret_val;

    gettimeofday(&uTime, NULL);
    srand(uTime.tv_usec);
    delta_val=max_val-min_val+1;
    ret_val=(rand())%delta_val+min_val;

    return ret_val;
}
